// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const { type, roomId, playerName, content, openid, row, col, player } = event

  switch (type) {
    case 'create_room':
      return await createRoom(roomId, playerName, openid)
    case 'join_room':
      return await joinRoom(roomId, playerName, openid)
    case 'make_move':
      return await makeMove(roomId, row, col, player, openid)
    case 'get_room_info':
      return await getRoomInfo(roomId)
    case 'leave_room':
      return await leaveRoom(roomId, playerName, openid)
    default:
      return {
        success: false,
        message: '未知的操作类型'
      }
  }
}

// 创建房间
async function createRoom(roomId, playerName, openid) {
  try {
    // 检查房间是否已存在
    const roomCheck = await db.collection('rooms').where({
      roomId: roomId
    }).get()

    if (roomCheck.data.length > 0) {
      return {
        success: false,
        message: '房间已存在'
      }
    }

    // 创建空棋盘
    const chessboard = createEmptyBoard()

    // 创建房间
    const result = await db.collection('rooms').add({
      data: {
        roomId: roomId,
        player1: openid,
        player2: null,
        status: 'waiting',
        chessboard: chessboard,
        currentPlayer: null,
        lastMove: null,
        winner: null,
        createTime: new Date(),
        lastUpdate: new Date(),
        gameStartTime: null
      }
    })

    return {
      success: true,
      data: {
        roomId: roomId,
        playerName: playerName
      }
    }
  } catch (error) {
    return {
      success: false,
      message: error.message
    }
  }
}

// 加入房间
async function joinRoom(roomId, playerName, openid) {
  try {
    const room = await db.collection('rooms').where({
      roomId: roomId
    }).get()

    if (room.data.length === 0) {
      return {
        success: false,
        message: '房间不存在'
      }
    }

    const roomData = room.data[0]
    
    // 检查房间是否已满
    if (roomData.player2) {
      return {
        success: false,
        message: '房间已满'
      }
    }

    // 检查玩家是否已在房间中
    if (roomData.player1 === openid) {
      return {
        success: false,
        message: '你已在房间中'
      }
    }

    // 添加玩家到房间
    await db.collection('rooms').where({
      roomId: roomId
    }).update({
      data: {
        player2: openid,
        status: 'playing',
        currentPlayer: 1, // 黑子先手
        gameStartTime: new Date()
      }
    })

    return {
      success: true,
      data: {
        roomId: roomId,
        playerName: playerName
      }
    }
  } catch (error) {
    return {
      success: false,
      message: error.message
    }
  }
}

// 下棋
async function makeMove(roomId, row, col, player, openid) {
  try {
    const room = await db.collection('rooms').where({
      roomId: roomId
    }).get()

    if (room.data.length === 0) {
      return {
        success: false,
        message: '房间不存在'
      }
    }

    const roomData = room.data[0]
    
    // 检查是否是当前玩家的回合
    if (roomData.currentPlayer !== player) {
      return {
        success: false,
        message: '不是你的回合'
      }
    }

    // 检查位置是否已被占用
    if (roomData.chessboard[row][col] !== 0) {
      return {
        success: false,
        message: '该位置已被占用'
      }
    }

    // 更新棋盘
    const newChessboard = roomData.chessboard.map(row => [...row])
    newChessboard[row][col] = player

    // 检查是否获胜
    const winner = checkWin(newChessboard, row, col, player)
    
    // 更新房间数据
    const updateData = {
      chessboard: newChessboard,
      lastMove: { row, col, player },
      lastUpdate: new Date()
    }

    if (winner) {
      updateData.winner = winner
      updateData.status = 'finished'
    } else {
      // 检查是否平局
      if (isBoardFull(newChessboard)) {
        updateData.winner = 0
        updateData.status = 'finished'
      } else {
        // 切换到下一个玩家
        updateData.currentPlayer = player === 1 ? 2 : 1
      }
    }

    await db.collection('rooms').where({
      roomId: roomId
    }).update({
      data: updateData
    })

    return {
      success: true,
      data: {
        row,
        col,
        player,
        winner: updateData.winner,
        status: updateData.status
      }
    }
  } catch (error) {
    return {
      success: false,
      message: error.message
    }
  }
}

// 获取房间信息
async function getRoomInfo(roomId) {
  try {
    const room = await db.collection('rooms').where({
      roomId: roomId
    }).get()

    if (room.data.length === 0) {
      return {
        success: false,
        message: '房间不存在'
      }
    }

    return {
      success: true,
      data: room.data[0]
    }
  } catch (error) {
    return {
      success: false,
      message: error.message
    }
  }
}

// 离开房间
async function leaveRoom(roomId, playerName, openid) {
  try {
    const room = await db.collection('rooms').where({
      roomId: roomId
    }).get()

    if (room.data.length === 0) {
      return {
        success: false,
        message: '房间不存在'
      }
    }

    const roomData = room.data[0]
    
    // 如果是房主离开，删除房间
    if (roomData.player1 === openid) {
      await db.collection('rooms').where({
        roomId: roomId
      }).remove()
    } else if (roomData.player2 === openid) {
      // 如果是第二个玩家离开，清空player2
      await db.collection('rooms').where({
        roomId: roomId
      }).update({
        data: {
          player2: null,
          status: 'waiting',
          currentPlayer: null,
          lastMove: null,
          winner: null
        }
      })
    }

    return {
      success: true,
      data: {
        roomId: roomId,
        playerName: playerName
      }
    }
  } catch (error) {
    return {
      success: false,
      message: error.message
    }
  }
}

// 创建空棋盘
function createEmptyBoard() {
  const board = []
  for (let i = 0; i < 15; i++) {
    board[i] = []
    for (let j = 0; j < 15; j++) {
      board[i][j] = 0
    }
  }
  return board
}

// 检查获胜
function checkWin(chessboard, row, col, player) {
  const directions = [
    [1, 0],   // 水平
    [0, 1],   // 垂直
    [1, 1],   // 对角线
    [1, -1]   // 反对角线
  ]

  for (const [dx, dy] of directions) {
    let count = 1

    // 向一个方向检查
    for (let i = 1; i < 5; i++) {
      const newRow = row + i * dx
      const newCol = col + i * dy
      if (newRow < 0 || newRow >= 15 || newCol < 0 || newCol >= 15 || chessboard[newRow][newCol] !== player) {
        break
      }
      count++
    }

    // 向相反方向检查
    for (let i = 1; i < 5; i++) {
      const newRow = row - i * dx
      const newCol = col - i * dy
      if (newRow < 0 || newRow >= 15 || newCol < 0 || newCol >= 15 || chessboard[newRow][newCol] !== player) {
        break
      }
      count++
    }

    if (count >= 5) {
      return player
    }
  }

  return null
}

// 检查棋盘是否已满
function isBoardFull(chessboard) {
  for (let i = 0; i < 15; i++) {
    for (let j = 0; j < 15; j++) {
      if (chessboard[i][j] === 0) {
        return false
      }
    }
  }
  return true
} 